/* util */
import { findComponentDownward } from '@src/util/assist';
import _ from 'lodash';
/* store */
import store, { BaseSelectUserVuexPropertyEnum } from '@src/component/common/BaseSelectUser/store';
/* type */
import { BaseBindTabFunOptions, BaseBindTabInfoOptions } from '@src/component/common/BaseSelectUser/model/interface';

/** 
 * @description 获取当前展示的tab
*/
export function useTabCurrent(){
    // @ts-ignore
    const rootVueInstance = document.querySelector('#app')!.__vue__ || {};
    // 查询tab列表找到当前展示的tab
    const frameViewComponent = findComponentDownward(rootVueInstance, 'frame-view');
    const frameTabs = frameViewComponent?.frameTabs || [];
    const currentTab = frameTabs.find((x: any) => x.show);
  
    return currentTab;
}

/** 
 * @description 获取绑定tab的选人组件列表
*/
export function useSelectUserBindTabInfo(): BaseBindTabInfoOptions{
    const bindTabInfo = store.state.bindTabInfo;
    return bindTabInfo;
}

/** 
 * @description 设置选人组件列表
*/
export function useSetStoreBindTabInfo(value: BaseBindTabInfoOptions): void{
    store.commit(BaseSelectUserVuexPropertyEnum.SetBindTabInfo, value);
}


/** 
 * @description store中当前绑定tab的选人组件
*/
export function useCurrentBindTabOption(): BaseBindTabFunOptions{
    const currentTab = useTabCurrent();
    const bindTabInfo = useSelectUserBindTabInfo();

    return bindTabInfo[currentTab.id] || {};
}

/** 
 * @description tab关闭或刷新时 销毁绑定选人组件
*/
export function useSelectUserBindTabClose(): void{
    const curTabOpt = useCurrentBindTabOption();

    // 删除store中存储的tab
    const bindTabInfo = useSelectUserBindTabInfo();
    const currentTab = useTabCurrent();

    if(!curTabOpt.close) return;
    curTabOpt?.close();

    delete bindTabInfo[currentTab.id];
    useSetStoreBindTabInfo(bindTabInfo);
}

/** 
 * @description 新增tab则隐藏全部选人组件
*/
export function useHiddenAllTab(): void{
    const bindTabInfo = useSelectUserBindTabInfo();
    for(let k in bindTabInfo){
        bindTabInfo[k].hidden();
    }
}

/** 
 * @description 切换tab隐藏其他 展示自己
*/
export function useHiddenOtherTab(id: string): void{
    const bindTabInfo = useSelectUserBindTabInfo();
    // if(!bindTabInfo[id]) return;

    for(let k in bindTabInfo){
        if(k === id){
            bindTabInfo[k].show();
        }else {
            bindTabInfo[k].hidden();
        }
    }
}